#include "ttServer.h"
#include "ttClientPrxMgr.h"
#include "myUtil.h"
#include "autoLock.h"
#include "ttMsgMap.h"

ttServer::ttServer()
{}

ttServer::~ttServer()
{}

DWORD WINAPI
ttServer::listenThread(LPVOID pParam)
{
	SOCKET sListen = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (INVALID_SOCKET == sListen){
		myUtil::testoutput("Invalid socket! %d\n",WSAGetLastError());
		return -1;
	}
	SOCKADDR_IN addr;
	addr.sin_family = AF_INET;
	addr.sin_port = htons(ttServer::c_Port);
	addr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);

	if (SOCKET_ERROR == bind(sListen,(SOCKADDR *)&addr,sizeof(SOCKADDR_IN))){
		myUtil::testoutput("Bind Failed!\n");
		return -1;
	}
	if (SOCKET_ERROR == listen(sListen,5)){
		myUtil::testoutput("Listen Failed!\n");
		return -1;
	}

	sockaddr_in client_addr;
	int addrLen = sizeof(client_addr);
	while (true){
		SOCKET sAccept = accept(sListen, (sockaddr far *)&client_addr, &addrLen);
		if (bRunning){
			ttClientPrxMgr::Get()->push_back(new ttClientProxy(sAccept));
		}
	}
	return 0;
}

int
ServerMe::move(float speed)
{
	{
		autoLock lock(ttClientPrxMgr::Get()->m_cs);
		for (ttClientPrxMgr::THISLIST::iterator iter = ttClientPrxMgr::Get()->getList().begin(); iter != ttClientPrxMgr::Get()->getList().end(); ++ iter){
			pttpack ppack = new ttpack;
			ppack->flag = ttpackflag::TP_CLIENTPRXMOVE;
			ppack->id = this->getID();
			ppack->x = this->getX();
			ppack->y = this->getY();
			ppack->btnUDDirection = this->getBtnUDDir();
			ppack->btnLRDirection = this->getBtnLRDir();
			ppack->direction = this->getDirection();
			ppack->bLRMoving = this->getLRMoving();
            ppack->bUDMoving = this->getUDMoving();
			ppack->speed = speed;
			{
				autoLock lock1((*iter)->m_cs);
				(*iter)->push_back(ppack);
			}
		}
	}
	__super::move(speed);
	return 0;
}

int
ServerMe::speak(WCHAR *sentence)
{
	{
		autoLock lock(ttClientPrxMgr::Get()->m_cs);
		for (ttClientPrxMgr::THISLIST::iterator iter = ttClientPrxMgr::Get()->getList().begin(); iter != ttClientPrxMgr::Get()->getList().end(); ++ iter){
			pttpack ppack = new ttpack;
			ppack->flag = ttpackflag::TP_CLIENTPRXSPEAK;
			ppack->id = this->getID();
			wsprintf(ppack->sentence, L"%s", sentence);
			wsprintf(ppack->name, this->getName());
			{
				autoLock lock((*iter)->m_cs);
				(*iter)->push_back(ppack);
			}
		}
	}
	return 0;
}

unsigned int
IDMaker::Get()
{
	static unsigned int id = 0;
	return ++ id;
}